// Copyright (C) 2005 Taylor L. Riche <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// $Id: dagtools.cc 61 2005-07-28 17:01:05Z richetl $
//
// -----------------------------------------------------------------

#include "dagtools.hh"

using namespace tt;

DagReader::DagReader(std::string fn) throw(std::invalid_argument) : TraceReader(fn)
{
  dagFile = fopen(filename.c_str(), "r");
  if(dagFile == NULL) {
    throw std::invalid_argument("The input trace specified does not exist.");
  }
  return;
}

DagReader::~DagReader()
{
  if(dagFile != NULL) {
    fclose(dagFile);
  }
  return;
}

void
DagReader::readPacket(Packet & newPacket) throw(std::underflow_error)
{
  DagFormat dagPacket;
  int amountRead;
  uint32_t data;
  
  for(uint32_t i = 0; i < sizeof(dagPacket); i += sizeof(data)) {
    amountRead = fread(&data, sizeof(data), 1, dagFile);
    if(amountRead != 1) {
      if(i != 0) {
 	throw std::underflow_error("Truncated dag trace file.");
      }
    }
    memcpy(((char*)&dagPacket) + i, &data, sizeof(data));
  }
  newPacket.tsSec = 0;
  newPacket.tsUSec = ntohl((dagPacket.timestamp >> 12) * 1000000 / 1048576);
  memcpy(&newPacket.ipHdr, dagPacket.payload, sizeof(iphdr));
  memcpy(&newPacket.tcpHdr, dagPacket.payload + sizeof(iphdr), sizeof(tcphdr));
  return;
}

void
DagWriter::writePacket(const Packet & targetPacket)
{
  DagFormat dagPacket;
  
  dagPacket.timestamp = ((htonl(targetPacket.tsUSec) * 1048576) / 1000000) << 12;
  // The following three values are filled in with 0.
  // This is for all practical purposes totally wrong.
  dagPacket.wand_crc = 0;
  dagPacket.atm_header = 0;
  dagPacket.llc_snap = 0;
  memcpy(dagPacket.payload, &targetPacket.ipHdr, sizeof(iphdr) + sizeof(tcphdr));
  fwrite(&dagPacket, sizeof(dagPacket), 1, dagFile);
  return;
}

DagWriter::DagWriter(std::string fn) throw(std::invalid_argument) : TraceWriter(fn)
{
  dagFile = fopen(filename.c_str(), "w");
  if(dagFile == NULL) {
    throw std::invalid_argument("There was an error opening the output file.");
  }
  return;
}

DagWriter::~DagWriter()
{
  if(dagFile != NULL) {
    fclose(dagFile);
  }
  return;
}
